﻿using System;
using System.Collections.Generic;
using System.Data;
using TidyBlog.Entity;
using TidyBlog.Data.Mapping;
using TidyBlog.Data;

namespace TidyBlog.DAL
{
    /// <summary>
    /// 用户数据层
    /// </summary>
    public class UserDAL
    {
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="user">用户</param>
        /// <returns>影响的行数</returns>
        public static int Create(User user)
        {
            return SimpleORM<User>.Insert(user);
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user">用户</param>
        /// <returns>影响的行数</returns>
        public static int Update(User user)
        {
            return SimpleORM<User>.Update(user);
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <returns>影响的行数</returns>
        public static int Delete(int userId)
        {
            return SimpleORM<User>.Delete(
                new User()
                {
                    UserId = userId
                }
            );
        }

        /// <summary>
        /// 读取用户
        /// </summary>
        /// <param name="user">用户</param>
        /// <returns>影响的行数</returns>
        public static User Read(int userId)
        {
            return SimpleORM<User>.Read(new User()
            {
                UserId = userId
            });
        }

        /// <summary>
        /// 根据昵称读取用户
        /// </summary>
        /// <param name="nickname">昵称</param>
        /// <returns>用户</returns>
        public static User Read(string nickname)
        {
            var cmd = DbHelper.CreateCommand((new SelectCommand(SimpleORM<User>.TableName))
                .Select("*")
                .Top(1)
                .Where(new WhereCondition("Nickname"))
                .ToString()
            );
            SimpleORM<User>.AttachParam(cmd, "Nickname", nickname);

            return SimpleORM<User>.DataReaderToEntity(DbHelper.ExecuteReader(cmd));
        }

        /// <summary>
        /// 根据用户名和密码读取用户
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="password">密码，如果密码为null，则只通过用户名读取</param>
        /// <returns>用户</returns>
        public static User Read(string userName, string password)
        {
            var cmd = DbHelper.CreateCommand();
            var selectCommand = new SelectCommand(SimpleORM<User>.TableName);
            var whereConditions = new List<WhereCondition>();

            whereConditions.Add(new WhereCondition("UserName"));
            SimpleORM<User>.AttachParam(cmd, "UserName", userName);
            if (password != null)
            {
                whereConditions.Add(new WhereCondition("Password"));
                SimpleORM<User>.AttachParam(cmd, "Password", password);
            }

            cmd.CommandText = selectCommand.Select("*").Top(1).Where(whereConditions).ToString();

            return SimpleORM<User>.DataReaderToEntity(DbHelper.ExecuteReader(cmd));
        }

        /// <summary>
        /// 检查某个用户名或昵称的用户是否存在
        /// </summary>
        /// <param name="name">名字</param>
        /// <returns>某个用户名或昵称的用户是否存在</returns>
        public static bool IsNameExist(string name)
        {
            var cmd = DbHelper.CreateCommand((new SelectCommand(SimpleORM<User>.TableName))
                .Select("COUNT(*)")
                .Where(new WhereCondition("UserName"))
                .ToString()
            );
            SimpleORM<User>.AttachParam(cmd, "UserName", name);

            return Convert.ToInt32(DbHelper.ExecuteScalar(cmd)) > 0;
        }

        /// <summary>
        /// 搜索用户
        /// </summary>
        /// <param name="conditions">搜索条件</param>
        /// <param name="pageSize">每页记录数</param>
        /// <param name="currentPage">当前页</param>
        /// <returns>搜索结果</returns>
        public static DataPaging<User> List(Dictionary<string, string> queryParams, ushort pageSize, int currentPage)
        {
            PagingHelper<User> pagingHelper = DbHelper.Provider.CreatePagingHelper<User>();
            var whereConditions = new List<WhereCondition>();

            if (queryParams != null)
            {
                if (queryParams.ContainsKey("username") && !String.IsNullOrEmpty(queryParams["username"]))
                {
                    whereConditions.Add(new WhereCondition("UserName") { Operator = WhereOperator.LIKE });
                    DbHelper.AttachParams(pagingHelper.Cmd,
                        DbHelper.CreateParam("UserName", "%" + queryParams["username"] + "%", DbType.String)
                    );
                }
                if (queryParams.ContainsKey("nickname") && !String.IsNullOrEmpty(queryParams["nickname"]))
                {
                    whereConditions.Add(new WhereCondition("Nickname") { Operator = WhereOperator.LIKE });
                    DbHelper.AttachParams(pagingHelper.Cmd,
                        DbHelper.CreateParam("Nickname", "%" + queryParams["nickname"] + "%", DbType.String)
                    );
                }
                if (queryParams.ContainsKey("groupid") && !String.IsNullOrEmpty(queryParams["groupid"]) && !queryParams["groupid"].Equals("0"))
                {
                    whereConditions.Add(new WhereCondition("GroupId"));
                    SimpleORM<User>.AttachParam(pagingHelper.Cmd, "GroupId", queryParams["groupid"]);
                }
            }
            pagingHelper.SQLCommand.Where(whereConditions);

            return pagingHelper.Execute(pageSize, currentPage);
        }
        
        /// <summary>
        /// 更新用户状态
        /// </summary>
        /// <param name="userId">用户编号</param>
        /// <param name="lastActivity">最后活动时间</param>
        /// <param name="lastIP">最后活动IP</param>
        /// <returns>影响的记录数</returns>
        public static int UpdateState(int userId, DateTime lastActivity, string lastIP)
        {
            var cmd = DbHelper.CreateCommand((new UpdateCommand(SimpleORM<User>.TableName))
                .Set(new[]
                {
                    new ColumnValuePair("LastActivity"),
                    new ColumnValuePair("LastIP")
                })
                .Where(new WhereCondition("UserId"))
                .ToString()
            );

            SimpleORM<User>.AttachParam(cmd, "LastActivity", lastActivity);
            SimpleORM<User>.AttachParam(cmd, "LastIP", lastIP);
            SimpleORM<User>.AttachParam(cmd, "UserId", userId);
            
            return DbHelper.ExecuteNonQuery(cmd);
        }
    }
}
